import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

const proto = Vue.prototype
Vue.use(VueRouter)

const files = require.context('.', false, /\.router.js$/)
const modules = []
files.keys().forEach(key => {
  modules.push(...files(key).default)
})


const routes = [
  {
    path: '*',
    redirect: '/agent/report'
  },
  ...modules
]

const router = new VueRouter({
  base: process.env.BASE_URL,
  linkActiveClass: 'is-active',
  routes
})

// 处理push导致的重定向异常
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

// 路由守卫
router.beforeEach((to, from, next) => {
  next()
  return
  if (store.state.user.isLogin) {
    if (to.name === 'Login') {
      next({ name:'AgentReport'});
      return;
    }
    next()
  } else {
    if(to.name === 'Login') {
      next();
      return;
    }
    next({ name: 'Login' })
  }
})

export default router
